package soa.security.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Name;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.util.UrlPathHelper;

import soa.security.Constants;
import soa.security.domain.Account;
import soa.security.domain.Applsystem;
import soa.security.domain.LdapTree;
import soa.security.domain.Organization;
import soa.security.web.LdapAuthenticationFilter;
import soa.security.web.export.LdapTreeJsonFormatExport;
import soa.security.web.support.action.LdapModelAction;
import v1.web.WebUtils;

/**
 * 
 * @author CY 2015-11-6 15:50:55
 *
 */
public class ApplsystemAction extends LdapModelAction<Applsystem> {

	private static final long serialVersionUID = -3556647618568340068L;

	private File file; // 上传的文件
	private String fileFileName;
	
	private Name dn;

	public Name getDn() {
		return dn;
	}

	public void setDn(Name dn) {
		this.dn = dn;
	}

	@Override
	protected Applsystem findByDn(String dn) {
		// TODO Auto-generated method stub
		return applsystemMgrService.findByDn(dn);
	}

	public String grid() {		
		//地区根目录下的应用系统查询方法
		updateResultContent(applsystemMgrService.allApplsystems_region_unit(parentDn,
				buildContext().getParameters()));
		
		//机构下的应用系统查询方法
//		if (StringUtils.isBlank(organizationId))
//			return SUCCESS;
//
//		if (StringUtils.isNotBlank(departmentId)) {
//			List<Applsystem> all = applsystemMgrService.allApplsystems(organizationId, buildContext().getParameters(),
//					subTree);
//			updateResultContent(applsystemMgrService.allApplsystems(all,
//					departmentMgrService.allApplsystems(organizationId, departmentId)));
//		} else
//			updateResultContent(
//					applsystemMgrService.allApplsystems(organizationId, buildContext().getParameters(), subTree));

		return SUCCESS;
	}

	public String edit() {
		Applsystem applsystem = getModel();
		if (StringUtils.isBlank(applsystem.getBid()))
			applsystem.setBid("AP" + applsystemMgrService.findMaxNumber(Applsystem.class));

		updateResultContent(applsystem);
		return SUCCESS;
	}

	protected Applsystem wrap(Applsystem applsystem) {
		if (applsystem == null)
			return applsystem;

		Organization or = applsystem.getOrganization();
		if (or == null)
			or = getOrganization(organizationId);

		applsystem.setOrganization(or);
		return applsystem;
	}

	public String view() {
		Applsystem applsystem = getModel();
		Organization or = applsystem.getOrganization();
		if (or == null)
			or = getOrganization(organizationId);
		applsystem.setOrganization(or);

		orId = applsystem.getOrganization().getBid();
		return SUCCESS;
	}

	public String doneSave() throws Exception {
		Applsystem appl = getModel();
		HttpServletRequest request = ServletActionContext.getRequest();
		if (getFile() != null) {
			InputStream in = null;
			try {
				in = new FileInputStream(getFile());
	
				String extension = FilenameUtils.getExtension(getFileFileName());
				String[] includeExts = { "img", "png", "bmp", "gif" };
	
				if (!ArrayUtils.contains(includeExts, extension)) {
					throw new Exception("不支持的文件后缀，只能导入img/png/bmp/gif文件");
				}
				
				String fileName = System.currentTimeMillis() + getFileFileName();
				
				// 创建一个文件输出流(windows和linux)
				FileOutputStream out = new FileOutputStream("src\\main\\webapp\\logo\\" + fileName);
				//FileOutputStream out = new FileOutputStream("../webapps/ROOT/logo/" + fileName);
				byte buffer[] = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
					appl.setLogo("\\logo\\" + fileName);
				}
				in.close();
				out.close();
			} catch (Exception e) {
				// TODO: handle exception
				log.error("上传失败", e);
				throw new Exception(e.getMessage());
			}
		}
		System.out.println("accountDns = " + accountDns);
		//获取登录账户所属机构
		HttpSession session = request.getSession(false);
		Organization or = (Organization)(session.getAttribute(LdapAuthenticationFilter.SESSION_ORGANIZATION_KEY));
		if (or != null) {
			applsystemMgrService.addApplsystemMgr_region(or.getBid(), appl, accountDns);
		} else {
			applsystemMgrService.addApplsystemMgr_region(appl, accountDns);
		}
		
		return SUCCESS;
	}

	public String doneUpdate() throws Exception {
		Applsystem appl = getModel();
		HttpServletRequest request = ServletActionContext.getRequest();
		if (getFile() != null) {
			InputStream in = null;
			try {
				in = new FileInputStream(getFile());
	
				String extension = FilenameUtils.getExtension(getFileFileName());
				String[] includeExts = { "img", "png", "bmp", "gif" };
	
				if (!ArrayUtils.contains(includeExts, extension)) {
					throw new Exception("不支持的文件后缀，只能导入img/png/bmp/gif文件");
				}
				
				String fileName = System.currentTimeMillis() + getFileFileName();

				// 创建一个文件输出流(windows和linux)
				FileOutputStream out = new FileOutputStream("src\\main\\webapp\\logo\\" + fileName);
				//FileOutputStream out = new FileOutputStream("../webapps/ROOT/logo/" + fileName);
				byte buffer[] = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
					appl.setLogo("\\logo\\" + fileName);
				}
				in.close();
				out.close();
			} catch (Exception e) {
				// TODO: handle exception
				log.error("上传失败", e);
				throw new Exception(e.getMessage());
			}
		}
		System.out.println("accountDns = " + accountDns);
		
		//获取登录账户所属机构
		HttpSession session = request.getSession(false);
		Organization or = (Organization)(session.getAttribute(LdapAuthenticationFilter.SESSION_ORGANIZATION_KEY));
		if (or != null) {
			applsystemMgrService.updateApplsystemMgr_region(or.getBid(), appl, accountDns);
		} else {
			applsystemMgrService.updateApplsystemMgr_region(appl, accountDns);
		}
		return SUCCESS;
	}

	public static String getLocation(HttpServletRequest request) {
		UrlPathHelper helper = new UrlPathHelper();
		StringBuffer buff = request.getRequestURL();
		String uri = request.getRequestURI();
		String origUri = helper.getOriginatingRequestUri(request);
		buff.replace(buff.length() - uri.length(), buff.length(), origUri);
		String queryString = helper.getOriginatingQueryString(request);
		if (queryString != null) {
			buff.append("?").append(queryString);
		}
		return buff.toString();
	}

	/**
	 * 获取登录账户所属机构下的账户
	 * 
	 * @return String
	 * @author CY 2015-11-10 09:43:17
	 */
	public String accountInOneOrgCheckTree() {
		//获取登录账户所属机构
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(false);
		Organization or = (Organization)(session.getAttribute(LdapAuthenticationFilter.SESSION_ORGANIZATION_KEY));
		List<LdapTree> trees = new ArrayList<LdapTree>();
		if (or != null) {
			List<Account> checked = applsystemMgrService.findAccounts(or.getBid(), Constants.APPLSYSTEMS, dnp);
			trees = treeMgrService.accountInOneOrgCheckTree(or.getBid(), checked);
		} else {
			trees = treeMgrService.adminTree("uid=admin,bid=RE0000", "admin", "admin");
		}
		
		LdapTreeJsonFormatExport content = new LdapTreeJsonFormatExport(trees);
		return WebUtils.writeJson(ServletActionContext.getResponse(), content.toString());
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
}
